<?php
namespace Home\Controller;
class WxController extends HomeController {
	private $token='twgdh';
    private $_appID="wxd1f405de3dde717e";
    private $_appsecret="b565258a04da186a1eefc12728c34fd3";
	public function index(){
	    $res=$this->checkSignature();
		if ($res && isset($_GET["echostr"])) {
			echo $_GET['echostr'];
		}else{
			$this->preson();
		}
	}
	public function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array($timestamp,$nonce,$this->token);
        sort($tmpArr,SORT_STRING);
        $tmpAtr = sha1(implode($tmpArr));
        if($tmpAtr==$signature){
		return true;
		}else{
		return false;
        }
     }
     public function preson(){
     	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
     	$obj = simplexml_load_string($xml);
     	if ($obj->MsgType=='event') {
     		if ($obj->Event=='subscribe') {
     			$str = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%d</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>';
                $msg = "欢迎";
                echo sprintf($str, $obj->FromUserName, $obj->ToUserName, time(), 'text', $msg);
     		}elseif ($obj->Event=='CLICK') {
                switch ($obj->EventKey) {
                    case 'k3':
                        $date = 'today';
                        $Content="请输入‘星座+运势’查看你的星座运势";
                        $this->textPush($obj,$Content);
                        break;
                }
            }
     	}elseif ($obj->MsgType=='text') {
             switch ($obj->Content) {
                case '1':
                
                 $arr = array(
                        array('Title' => '百度', 'Description' => '百度一下', 'PicUrl' => 'https://www.baidu.com/img/bd_logo1.png', 'Url' => 'https://www.baidu.com/'),
                        array('Title' => '网易', 'Description' => '网易首页', 'PicUrl' => 'https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=2490895003,2642262494&fm=58&s=2370E532CFA568134854D6FC0300F020', 'Url' => 'http://www.163.com/'),
                    );
                 $this->picpush($obj,$arr);
                    break;
                // case '2':
                //     $Content=$this->getaccesstoken();
                //     //$Content=$Content['access_token'];
                //     $this->textPush($obj,$Content);
                //     break;
                default:
                if (mb_substr($obj->Content,-2)=='天气') {
                    $city=mb_substr($obj->Content,0,-2);
                    $res=$this->weather($city);
                    $this->weatherModer($res,$obj->FromUserName);
                    break;
                }elseif(mb_substr($obj->Content,-2)=='运势'){
                    $xing=mb_substr($obj->Content,0,-2);
                    $res=$this->horoscope($xing);
                    $this->horoscopeModer($res,$obj->FromUserName,$xing);
                    break;
                }else{
                    $content=$this->robot($obj->Content,substr($obj->FromUserName,0,5));
                    $this->textPush($obj,$content);
                    break;
                }
                    
             }
     	}
     }
     public function picpush($obj,$arr){
            $str .= '<xml>
                    <ToUserName><![CDATA['.$obj->FromUserName.']]></ToUserName>
                    <FromUserName><![CDATA['.$obj->ToUserName.']]></FromUserName>
                    <CreateTime>'.time().'</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>'.count($arr).'</ArticleCount>
                    <Articles>';
            foreach ($arr as $v) {
             $str .= '<item>
                    <Title><![CDATA['. $v['Title'] .']]></Title>
                    <Description><![CDATA['. $v['Description'] .']]></Description>
                    <PicUrl><![CDATA['. $v['PicUrl'] .']]></PicUrl>
                    <Url><![CDATA['. $v['Url'] .']]></Url>
                    </item>';
                }
            $str .= '</Articles>
                    </xml>';
            echo $str;          
     }
     public function getaccesstoken(){
         $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appID}&secret={$this->_appsecret}";
         if (S('access_token')==null) {
            $access_token=$this->curlSub($url);
            S('access_token',$access_token['access_token'],$access_token['expires_in']-200); 
         }
         return S('access_token');
     }
    //文字推送
    private function textPush($obj,$content){
        $str = '
        <xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%d</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
        </xml>';
        echo sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),'text',$content);
    }
private function curlSub($url,$post){
        //1.初始化
        $ch = curl_init();
        //2.相关设置
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (stripos($url, "https://") !== false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if($post != null){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);    
        }
        //3.执行
        $res = curl_exec($ch);

        //当遇到错误的时候，我们可以将curl的错误打印出来
        if(curl_errno($ch) != 0){
            var_dump("错误号是".curl_errno($ch)."错误原因".curl_error($ch));
        }
        //4.关闭
        curl_close($ch);
        return json_decode($res,true);
    }
    /**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     */
    public static function json_encode($arr)
    {
        $parts   = array();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys       = array_keys($arr);
        $max_length = count($arr) - 1;
        if (($keys[0] === 0) && ($keys[$max_length] === $max_length)) {
            //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for ($i = 0; $i < count($keys); $i++) {
                //See if each key correspondes to its position
                if ($i != $keys[$i]) {
                    //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ($arr as $key => $value) {
            if (is_array($value)) {
                //Custom handling for arrays
                if ($is_list) {
                    $parts[] = self::json_encode($value);
                }
                /* :RECURSION: */
                else {
                    $parts[] = '"' . $key . '":' . self::json_encode($value);
                }
                /* :RECURSION: */
            } else {
                $str = '';
                if (!$is_list) {
                    $str = '"' . $key . '":';
                }

                //Custom handling for multiple data types
                if (is_numeric($value) && $value < 2000000000) {
                    $str .= $value;
                }
                //Numbers
                elseif ($value === false) {
                    $str .= 'false';
                }
                //The booleans
                elseif ($value === true) {
                    $str .= 'true';
                } else {
                    $str .= '"' . addslashes($value) . '"';
                }
                //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts[] = $str;
            }
        }
        $json = implode(',', $parts);
        if ($is_list) {
            return '[' . $json . ']';
        }
        //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }
    //删除自定义菜单
    public function delMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$this->getaccesstoken()}";
        $res = $this->curlSub($url);
        
    }
    public function customMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->getaccesstoken()}";
        $arr = [
            'button'=>[
                [
                    'type'=>'view',
                    'name'=>'每日一片',
                    'url'=>'http://www.luluhei.co/',
                ],
              
                [
                    'name'=>'菜单',
                    'sub_button'=>[
                        [
                            'type'=>'view',
                            'name'=>'百度一下',
                            'url'=>'http://www.baidu.com/',
                        ],
                        [
                            'type'=>'pic_photo_or_album',
                            'name'=>'微信相册发图',
                            'key'=>'k2',
                            'sub_button'=>[],
                        ],
                        [
                            'type'=>'click',
                            'name'=>'星座运势',
                            'key'=>'k3',
                        ],
                    ],
                ],
            ],
        ];
        $res = $this->curlSub($url,$this->json_encode($arr));
    }
    public function robot($info='',$obj){
        $url="http://op.juhe.cn/robot/index?info={$info}&key=18c7dcaa501f00a193443e0d0bad3b31&userid={$obj}";
        $res=$this->curlSub($url);
        if ($res["result"]["code"]==100000) {
            return $res["result"]["text"];
        }else{
            die('小编出差了');
        }
        
    }
    public function weather($city=''){
        $city = urlencode($city);
        $url="http://v.juhe.cn/weather/index?cityname={$city}&key=fb2709a9902d97ea1575bc171f721f90";
        $res=$this->curlSub($url);
        return $res['result'];
    }
    private function weatherModer($res,$userid){
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$this->getaccesstoken()}";
        $arr = [
            'touser'=>$userid,
            'template_id'=>'fakf05cGCi-oR5uSTdXZthMM_7zL2nA4F8Vd5OkGB20',
            'url'=>"https://www.baidu.com/s?wd={$obj->Content}",
            'data'=>[
                'city'=>[
                    'value'=>$res['today']['city'],
                    'color'=>'#000',
                ],

                'week'=>[
                    'value'=>$res['today']['week'],
                    'color'=>'#000',
                ],

                'temperature'=>[
                    'value'=>$res['today']['temperature'],
                    'color'=>'#000',
                ],

                'weather'=>[
                    'value'=>$res['today']['weather'],
                    'color'=>'#000',
                ],

                'wind'=>[
                    'value'=>$res['today']['wind'],
                    'color'=>'#000',
                ],

            ],

        ];
        $this->curlSub($url,$this->json_encode($arr));
    }
    public function horoscope($xing=''){
        $xing=urlencode($xing);
        $url="http://web.juhe.cn:8080/constellation/getAll?consName={$xing}&key=ce2ce0dfd802e7ff250cdf87fc66822e";
        $res=$this->curlSub($url);
        if ($res) {
            return $res;
        }else{
            die;
        }
        
    }
    public function prfor(){
        $url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->getaccesstoken()}";
        $post='{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "123"}}}';
        $res=$this->curlSub($url,$post);
        $url2="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$res['ticket']}";
        return $url2;
    }


    private function horoscopeModer($res,$userid,$xing){
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$this->getaccesstoken()}";
        $arr = [
            'touser'=>$userid,
            'template_id'=>'BrAZFn5i7mEB1RPT7yziWV5SU-P_3SauE8hhQNY0gEo',
            'url'=>"http://www.fashiondong.xin/Home/Xinzuo?xing=$xing",
            'data'=>[
                'name'=>[
                    'value'=>$res['today']['name'],
                    'color'=>'#000',
                ],

                'datetime'=>[
                    'value'=>$res['today']['datetime'],
                    'color'=>'#000',
                ],

                'all'=>[
                    'value'=>$res['today']['all'],
                    'color'=>'#000',
                ],

                'color'=>[
                    'value'=>$res['today']['color'],
                    'color'=>'#000',
                ],

                'health'=>[
                    'value'=>$res['today']['health'],
                    'color'=>'#000',
                ],

                'love'=>[
                    'value'=>$res['today']['love'],
                    'color'=>'#000',
                ],

                'QFriend'=>[
                    'value'=>$res['today']['QFriend'],
                    'color'=>'#000',
                ],
                'summary'=>[
                    'value'=>$res['today']['summary'],
                    'color'=>'#000',
                ],
            ],

        ];
        $this->curlSub($url,$this->json_encode($arr));
    }

}


?>